package com.itheima.controller;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.itheima.config.MyConfig;
import com.itheima.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/notify")
public class WxPayController {

    @Autowired
    private OrdersService ordersService;

    //返回一个支付成功页面
    //用户支付完成后，微信会调用这个接口
    @PostMapping()
    public void notifyWx(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //流数据IO
        //告诉商家，哪个订单支付成功
        String string = convertToString(request.getInputStream());
        //把xml 请求参数转换成一个Map
        Map<String, String> map = WXPayUtil.xmlToMap(string);
        //1.支付的订单号  哪个订单支付的
        //2.微信订单号（流水号）  后期退款需要用到的
        String transaction_id = map.get("transaction_id");
        //3.return_code 代表是否返回的是成功
        String return_code = map.get("return_code");
        if (return_code.equals("SUCCESS")) {//代表支付成功
            //4.根据订单号，查询微信端的支付状态
            String out_trade_no = map.get("out_trade_no");
            //调用微信的查询订单接口来查询此订单是否真的支付成功
            boolean flag = checkOrderStatus(out_trade_no); //确认
            if (flag) {//代表真的支付了。修改订单状态为已支付即可
                ordersService.updateStatus(out_trade_no, transaction_id);
                //告诉微信，瑞吉收到消息了
                //获取支付成功的订单。然后修改数据的订单状态为已支付
                response.setContentType("text/xml");
                String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                response.getWriter().write(data);
            }
        }
    }


    private boolean checkOrderStatus(String out_trade_no) throws Exception {

        WXPay wxPay = new WXPay(new MyConfig());

        Map<String, String> map = new HashMap<>();
        map.put("out_trade_no", out_trade_no);
        Map<String, String> responseMap = wxPay.orderQuery(map);
        String trade_state = responseMap.get("trade_state");
        return trade_state.equals("SUCCESS");
    }

    /**
     * 输入流转换为xml字符串
     *
     * @param inputStream
     * @return
     */
    public static String convertToString(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inputStream.close();
        String result = new String(outSteam.toByteArray(), "utf-8");
        return result;
    }
}
